import { BrowserRouter as Router } from 'react-router-dom'
import { FC, memo, useState, useEffect } from 'react'
import { Provider } from 'react-redux'
import { renderRoutes } from 'react-router-config'
import { connect } from 'react-redux'
import { getUserInfoAction } from 'src/redux/actions/UserActions'
import { Spin } from 'antd'
import { LoadingWrap } from '@/assets/styles/app_style'

// Import store
import store from 'src/redux/store'

// Import route
import routes from 'src/routes'

// Import Ware Effect
import Wave from 'node-waves'

// Import scss
import './App.scss'
import '@/styles/index.scss'

// Init Wave Effect
Wave.init()

// Types
interface GuardProps {
    token: string | undefined
    getUserInfo: () => any
}

const App: FC<GuardProps> = (props) => {
    const { getUserInfo, token } = props
    const [loading, setLoading] = useState(!!token)

    useEffect(() => {
        console.log('app useEffect')
        const init = async () => {
            if (!token) return
            await getUserInfo()
            setLoading(false)
        }

        init()
    // eslint-disable-next-line
    }, [token])

    return (
        <>
            {loading ? (
                <LoadingWrap>
                    <Spin size={'large'} />
                </LoadingWrap>
            ) : (
                <Router>
                    { renderRoutes(routes) }
                </Router>
            )}
        </>
    )
}

const mapStateToProps = (state: any) => ({
    token: state.user.token,
})

const mapActionToProps = {
    getUserInfo: getUserInfoAction
}

const AppBox = () => {
    const AppComponent = connect(mapStateToProps, mapActionToProps)(memo(App))
    return (
        <Provider store={store}>
            <AppComponent />
        </Provider>
    )
}

export default AppBox
